package com.guanghua.brick.html.tag;

import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.guanghua.brick.html.Constant;
import com.guanghua.brick.util.IConfig;
import com.guanghua.brick.util.XmlReader;

public class WebAppContextTag extends BodyTagSupport {
	
	private static Log logger = LogFactory.getLog(WebPageHeaderTag.class);
	
	public int doEndTag() throws JspException {
		String head = getWebAppContext(pageContext);
		try {
			pageContext.getOut().println(head);
		} catch (IOException e) {
			logger.error("io exception on print head", e);
		}
		
		return BodyTagSupport.EVAL_PAGE;
	}
	
	
	/**
	 * 获取初始化配置在brick.web.xml中的 web app context信息
	 * @return
	 */
	public static String getWebAppContext(ServletContext sc) {
		//从servletcontext中获取，如果没有就重新初始化
		String context = (String)sc.getAttribute(Constant.WEB_APP_CONTEXT);
		if (context == null) {
			try {
				//读取配置
				XmlReader reader = new XmlReader(sc.getRealPath("/WEB-INF/brick.web.xml"), true);
				IConfig[] c = reader.readByTagName("web-app-context");
				if (c != null && c.length != 0 && c[0] != null)
					context = c[0].getText();
				else 
					context = "";
				
				//放入servletcontext中
				sc.setAttribute(Constant.WEB_APP_CONTEXT, context);
			} catch (Exception e) {
				logger.error("parse xml /web-inf/brick.web.xml to find web context error", e);
				context = "";
			}
		}
		
		return context.equals("/")? "":"/" + context;
	}
	
	public static String getWebAppContext(PageContext pageContext) {
		return getWebAppContext(pageContext.getServletContext());
	}
	
	public static String getWebAppContext(HttpServletRequest request) {
		return getWebAppContext(request.getSession().getServletContext());
	}
}
